package org.brisling.sysman.service;

import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.brisling.base.domain.ListDomain;
import org.brisling.base.domain.RetDomain;
import org.brisling.common.ConstSysParam;
import org.brisling.common.SysConfig;
import org.brisling.common.util.ConvertUtil;
import org.brisling.common.util.FileUtil;
import org.brisling.common.util.LongUtil;
import org.brisling.common.util.ScaleImgUtil;
import org.brisling.sysman.domain.UploadFiles;
import org.brisling.sysman.queryService.QueryUploadService;
import org.brisling.sysman.repository.UploadFileRepo;
import org.brisling.sysman.service.base.BaseSysmanService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;


@RestController
@RequestMapping("/upload")
/**
 * 用戶后台服務service
 * @Author : jackson wang
 * @Date   : 2015年6月8日 下午4:18:01
 * @version: 1.0
 */
public class UploadService extends BaseSysmanService<UploadFiles>{
	
	@SuppressWarnings("unused")
	@Autowired
	private UploadFileRepo baseRepo;
	
	private String upload_path = "d:/upload";
	
	private String upload_bizcode = "archive";
	
	private static Logger logger = LoggerFactory.getLogger(UploadService.class);
	
	@Autowired
	private QueryUploadService qryUploadService;
	
	public UploadService(){
		this.moduleName = ConstSysParam.MODULE_UPLOAD;
	}
	
	/**
	 * 获取业务主页面 
	 * @return
	 */
	@RequestMapping("/mainPage.action")
	public ModelAndView getMainPage(){
		return getBizMainPage();
	}
	
	/**
	 * 获取业务编辑页面
	 * @return
	 */
	@RequestMapping("/editPage.action")
	public ModelAndView getEditPage(){
		return getBizEditPage();
	}
	
	/**
	 * 获取指定名称页面
	 * @param code
	 * @return
	 */
	@RequestMapping("/getPage.action")
	public ModelAndView getPage(@RequestParam(value="code",required=false) String code){
		String _code =code ==null?"main":code;
		return new ModelAndView("/sysman/sysman_upload/"+_code);
	}
	
	/**
	 * 获取指定名称页面
	 * @param code
	 * @return
	 */
	@RequestMapping("/getExternalPage.action")
	public ModelAndView getExternalPage(@RequestParam(value="code",required=false) String code){
		String _code =code ==null?"main":code;
		return new ModelAndView("/"+_code);
	}
	
	/**
	 * 获取业务编辑页面
	 * @return
	 */
	@RequestMapping("/uploadfivePage.action")
	public ModelAndView getUploadfivePage(){
		return new ModelAndView("/sysman/sysman_upload/uploadfive");
	}
	
	/**
	 * 获取业务编辑页面
	 * @return
	 */
	@RequestMapping("/uploadPicPage.action")
	public ModelAndView getUploadpicPage(){
		return new ModelAndView("/sysman/sysman_upload/uploadPic");
	}
	
	/**
	 * 分页查询用户列表页面
	 * @param deptid
	 * @param page
	 * @param rows
	 * @param sort
	 * @return
	 */
	@RequestMapping("/getListDomain.action")
	public ListDomain<UploadFiles> getListDomain(
			@RequestParam(value="page",required=false) String page,
			@RequestParam(value="rows",required=false) String rows,
			@RequestParam(value="sort",required=false) String sort){
		
				
		return super.getPagedList(page, rows);
			
	}
	
	/**
	 * 分页查询用户列表页面
	 * @param deptid
	 * @param page
	 * @param rows
	 * @param sort
	 * @return
	 */
	@RequestMapping("/getImageListDomain.action")
	public ListDomain<UploadFiles> getImageListDomain(
			@RequestParam(value="page",required=false) String page,
			@RequestParam(value="rows",required=false) String rows,
			@RequestParam(value="sort",required=false) String sort){
		
				
		return super.getPagedList(page, rows);
			
	}
	
	
	
	/**
	 * 分页查询用户列表页面
	 * @param deptid
	 * @param page
	 * @param rows
	 * @param sort
	 * @return
	 */
	@RequestMapping("/getList.action")
	public List<UploadFiles> getPagedListRows(
			@RequestParam(value="page",required=false) String page,
			@RequestParam(value="rows",required=false) String rows,
			@RequestParam(value="sort",required=false) String sort){
		
		
			return super.getAll(page,rows,getSort(sort));
			
	}
	
	/**
	 * 删除记录,单条或批量删除记录,id不为空，执行单条删除，id为空且ids不为空，执行批量删除
	 * @param id	待删除的单条记录id
	 * @param ids	待删除的多条记录id，以','分隔
	 * @return
	 */
	@RequestMapping("/del.action")
	public RetDomain delRow(@RequestParam(value="id",required=false) Long id,@RequestParam(value="ids",required=false) String ids){
				
		return super.delRows(id, ids);		 
	}
	
	/**
	 * 删除记录,单条或批量删除记录,id不为空，执行单条删除，id为空且ids不为空，执行批量删除
	 * @param id	待删除的单条记录id
	 * @param ids	待删除的多条记录id，以','分隔
	 * @return
	 */
	@RequestMapping("/flowDel.action")
	public RetDomain delFlowRow(@RequestParam(value="id",required=false) Long id,@RequestParam(value="ids",required=false) String ids){
		
			return delRow(id,ids);
		
	}
	
	
	/**
	 * 保存单条记录
	 * @param id
	 */
	@RequestMapping("/save.action")
	public UploadFiles save(@RequestBody String body){
		UploadFiles obj = bodyToObj(body, UploadFiles.class);		
		super.save(obj);
		return obj;
	}
	
	/**
	 * 批量保存附件记录
	 * @param bizno
	 * @param bizcode
	 * @param oldBizno
	 * @return
	 */	
	@RequestMapping("/saveList.action")
	public RetDomain saveList(String[] bizno,String bizcode,String oldBizno){
		
		UploadFiles uf =qryUploadService.getOneByField("bizno", oldBizno);
		List<UploadFiles> lists = new ArrayList<UploadFiles>();
		for(int i=0;i<bizno.length;i++){
			UploadFiles newuf = new UploadFiles();
			newuf.setBizcode(bizcode);
			newuf.setBizno(bizno[i]);
			newuf.setFilename(uf.getFilename());
			newuf.setSavedFileName(uf.getSavedFileName());
			newuf.setFiletype(uf.getFiletype());
			lists.add(newuf);
		}
		return super.saveList(lists);
		
	}
	
	/**
	 * 批量保存附件记录
	 * @param lists	附件记录集合
	 * @return
	 */
	
	public Iterable<UploadFiles> saveBatch(List<UploadFiles> lists){
		
		return baseRepo.save(lists);		
		
	}
	
	
	/**
	 * 保存单一图片记录
	 * @param bizno
	 * @param bizcode
	 * @param oldBizno
	 * @return
	 */	
	@RequestMapping("/uploadPic.action")
	public Map<String,String> uploadPic(HttpServletRequest request,HttpServletResponse response){	
		
		//获取前台传递的附件参数
		MultipartHttpServletRequest mulRequest = (MultipartHttpServletRequest) request;
		
		Map<String,MultipartFile> map = mulRequest.getFileMap();
		
		Map<String,String[]> paramMap =mulRequest.getParameterMap();
		
		MultipartFile apkFile = map.get("img");
		
		//定义返回变量
		Map<String,String> retMap = new HashMap<String,String>();
		
		//定义默认图片大小
		String initW = "150";
		
		String initH = "180";
		
		//判断前台参数合法性
		if(paramMap.containsKey("bizno") && paramMap.containsKey("bizcode")){
			UploadFiles uf = new UploadFiles();
			String[] ids = paramMap.get("bizno");
			if((ids!=null) && (ids.length>0)){
				uf.setBizno(ids[0]);
			}
			
			String[] fbc = paramMap.get("bizcode");
			if((fbc!=null)&&(fbc.length>0)){
				uf.setBizcode(fbc[0]);					
			}
			
			if(paramMap.containsKey("width")){
				Object obj = paramMap.get("width");
				initW = obj==null?initW:obj.toString();
			}
			
			if(paramMap.containsKey("height")){
				Object obj = paramMap.get("height");
				initH = obj==null?initH:obj.toString();
			}
			
			
			String _fileName = apkFile.getOriginalFilename();
			
			if(_fileName !=null){						
				try {
					_fileName =new String(_fileName.getBytes("ISO-8859-1"),"UTF-8");
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				uf.setFilename(_fileName);
				
				
				UUID uuid = UUID.randomUUID();
				String savedFileName = null;
				String[] _token = _fileName.split(".");
				if(_token.length>0){
					savedFileName = String.format("%2$s.%3$s", uuid.toString(),_token[_token.length-1]);
				}else{
					savedFileName = uuid.toString();
				}
				uf.setSavedFileName(savedFileName);
			}
			
			if(apkFile.getContentType()!=null){
				uf.setFiletype(apkFile.getContentType());
			}
			
//			super.save(uf);
			UploadFiles savedUF = saveFile(uf,apkFile);
			
			retMap.put("id", uf.getId().toString());
			retMap.put("url", "/portal/getImage.action?id="+uf.getId());
			retMap.put("status", "success");
		}else{
			retMap.put("status", "error");
		}
		
		
		//获取上传文件信息
		
		//保存上传文件并获取保存后的文件id
		
		
		
		//生成返回信息
		
		//状态信息
		
		
		
		
		retMap.put("width", initW);
		
		retMap.put("height", initH);
		
		
		
		return retMap;
		
	}
	/**
	 * 批量保存附件记录
	 * @param bizno
	 * @param bizcode
	 * @param oldBizno
	 * @return
	 */	
	
	public String saveOne(UploadFiles uf){	
		
		super.save(uf);
		
		return "200";
		
	}
	
	/**
	 * 发布流程定义文件
	 * @param request
	 * @return	发布状态字符
	 */
	@RequestMapping(value = "/uploadifive.action")	
	@ResponseBody	
	public String uploadifive(@RequestBody(required=false) String body,HttpServletRequest request) {
	
		MultipartHttpServletRequest mulRequest = (MultipartHttpServletRequest) request;
		
		Map<String,MultipartFile> map = mulRequest.getFileMap();
	    
		Map<String,String[]> paramMap =mulRequest.getParameterMap();
		
		MultipartFile apkFile = map.get("Filedata");
		
		if((paramMap !=null) && (!paramMap.isEmpty()) && (apkFile!=null)){
			
			if(paramMap.containsKey("bizno") && paramMap.containsKey("bizcode")){
				UploadFiles uf = new UploadFiles();
				String[] ids = paramMap.get("bizno");
				if((ids!=null) && (ids.length>0)){
					uf.setBizno(ids[0]);
				}
				
				String[] fbc = paramMap.get("bizcode");
				if((fbc!=null)&&(fbc.length>0)){
					uf.setBizcode(fbc[0]);					
				}
				
				String _fileName = apkFile.getOriginalFilename();
				
				if(_fileName !=null){						
					try {
						_fileName =new String(_fileName.getBytes("ISO-8859-1"),"UTF-8");
					} catch (UnsupportedEncodingException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
					uf.setFilename(_fileName);
					
					
					UUID uuid = UUID.randomUUID();
					String savedFileName = null;
					String[] _token = _fileName.split(".");
					if(_token.length>0){
						savedFileName = String.format("%2$s.%3$s", uuid.toString(),_token[_token.length-1]);
					}else{
						savedFileName = uuid.toString();
					}
					uf.setSavedFileName(savedFileName);
				}
				
				if(apkFile.getContentType()!=null){
					uf.setFiletype(apkFile.getContentType());
				}
				
//				super.save(uf);
				UploadFiles savedUF = saveFile(uf,apkFile);
				if(savedUF!=null && savedUF.getId()!=null )
					return "200";
			}
			
		}
	    return "500";
	    
	
	    
	}
	
	/**
	 * 发布流程定义文件
	 * @param request
	 * @return	发布状态字符
	 */
	@RequestMapping(value = "/uploadCkeditor.action")	
	@ResponseBody	
	public String uploadCkeditor(@RequestBody(required=false) String body,HttpServletRequest request,HttpServletResponse response) {
	
		MultipartHttpServletRequest mulRequest = (MultipartHttpServletRequest) request;
		
		Map<String,MultipartFile> map = mulRequest.getFileMap();
	    
		Map<String,String[]> paramMap =mulRequest.getParameterMap();
		
		
		
		String fileUrl = "/portal/getFile?id=";
		
		MultipartFile apkFile = map.get("upload");
		StringBuilder sb = null;
		if((paramMap !=null) && (!paramMap.isEmpty()) && (apkFile!=null)){
			
			//获取ckedit回调参数
			String CKEditorFuncNum = null;
			if(paramMap.containsKey("CKEditorFuncNum")){
				Object[] obj = paramMap.get("CKEditorFuncNum");
				if(obj!=null && obj.length>0)
				CKEditorFuncNum = obj[0].toString();
			}		
			
			
			UploadFiles uf = new UploadFiles();
			//生成文件名
			String _fileName = apkFile.getOriginalFilename();
			
			if(_fileName !=null){						
				try {
					_fileName =new String(_fileName.getBytes("ISO-8859-1"),"UTF-8");
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				uf.setFilename(_fileName);
				
				
				UUID uuid = UUID.randomUUID();
				String savedFileName = null;
				String[] _token = _fileName.split(".");
				if(_token.length>0){
					savedFileName = String.format("%1$s.%2$s", uuid.toString(),_token[_token.length-1]);
				}else{
					savedFileName = uuid.toString();
				}
				uf.setSavedFileName(savedFileName);
			}
			
			//设置文件类型
			if(apkFile.getContentType()!=null){
				uf.setFiletype(apkFile.getContentType());
			}
			
			//设置文件业务代码及业务编号
			uf.setBizcode(ConstSysParam.CK_BIZCODE);
			if(paramMap.containsKey("bizno")){
				Object obj = paramMap.get("bizno");
				if(obj!=null){
					uf.setBizno(obj.toString());
				}
			}
			//保存文件
			UploadFiles savedUF = saveFile(uf,apkFile);
			
				
			//回写上传文件
			
			//设置ckeditortab页跳转
			if(savedUF!=null && savedUF.getId()!=null ){
				//非图片文件类型
				sb = new StringBuilder();
				sb.append("<script type='text/javascript'>");
				sb.append("window.parent.CKEDITOR.tools.callFunction(%1$s,'%2$s','%3$s');");
				sb.append("</script>");
				
				
				String outMsg =String.format(sb.toString(), CKEditorFuncNum,fileUrl + savedUF.getId(),"");
				
				try {
					response.getOutputStream().write(outMsg.getBytes());
					response.flushBuffer();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
			return "200";
		}
	    return "500";
	    
	
	    
	}
	
	/**
	 * 发布流程定义文件
	 * @param request
	 * @return	发布状态字符
	 */
	@RequestMapping(value = "/uploadCkeditorImage.action")	
	@ResponseBody	
	public String uploadCkeditorImage(String body,HttpServletRequest request,HttpServletResponse response) {
	
		MultipartHttpServletRequest mulRequest = (MultipartHttpServletRequest) request;
		
		Map<String,MultipartFile> map = mulRequest.getFileMap();
	    
		Map<String,String[]> paramMap =mulRequest.getParameterMap();
		
		String fileTypeErr = "'文件格式不正确(必须为.jpg/.gif/.bmp/.png文件)'";
		
		String fileUrl = "/portal/getImage?id=";
		
		MultipartFile apkFile = map.get("upload");
		StringBuilder sb = null;
		if((paramMap !=null) && (!paramMap.isEmpty()) && (apkFile!=null)){
			
			//获取ckedit回调参数
			String CKEditorFuncNum = null;
			if(paramMap.containsKey("CKEditorFuncNum")){
				Object[] obj = paramMap.get("CKEditorFuncNum");
				if(obj!=null && obj.length>0)
				CKEditorFuncNum = obj[0].toString();
			}
			
			//判断文件类型
			String fileType = apkFile.getContentType();
			if(fileType!=null){
				int _index = fileType.indexOf("image");
				
				if(_index<0){
					//非图片文件类型
					sb = new StringBuilder();
					sb.append("<script type=\"text/javascript\">");
					sb.append("window.parent.CKEDITOR.tools.callFunction(%1$s,'',%2$s)");
					sb.append("</script>");
					String outMsg =String.format(sb.toString(), CKEditorFuncNum,fileTypeErr);
					
					try {
						response.getOutputStream().write(outMsg.getBytes());
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					return null;
				}
			}
			
			
			UploadFiles uf = new UploadFiles();
			//生成文件名
			String _fileName = apkFile.getOriginalFilename();
			
			if(_fileName !=null){						
				try {
					_fileName =new String(_fileName.getBytes("ISO-8859-1"),"UTF-8");
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				uf.setFilename(_fileName);
				
				
				UUID uuid = UUID.randomUUID();
				String savedFileName = null;
				String[] _token = _fileName.split(".");
				if(_token.length>0){
					savedFileName = String.format("%1$s.%2$s", uuid.toString(),_token[_token.length-1]);
				}else{
					savedFileName = uuid.toString();
				}
				uf.setSavedFileName(savedFileName);
			}
			
			//设置文件类型
			if(apkFile.getContentType()!=null){
				uf.setFiletype(apkFile.getContentType());
			}
			
			//设置文件业务代码及业务编号
			uf.setBizcode(ConstSysParam.CK_BIZCODE);
			if(paramMap.containsKey("bizno")){
				Object obj = paramMap.get("bizno");
				if(obj!=null){
					uf.setBizno(obj.toString());
				}
			}
			//保存文件
			UploadFiles savedUF = saveFile(uf,apkFile);
			
				
			//回写上传文件
			
			//设置ckeditortab页跳转
			if(savedUF!=null && savedUF.getId()!=null ){
				//非图片文件类型
				sb = new StringBuilder();
				sb.append("<script type='text/javascript'>");
				sb.append("window.parent.CKEDITOR.tools.callFunction(%1$s,'%2$s','%3$s');");
				sb.append("</script>");
				
				
				String outMsg =String.format(sb.toString(), CKEditorFuncNum,fileUrl + savedUF.getId(),"");
				
				try {
					response.getOutputStream().write(outMsg.getBytes());
					response.flushBuffer();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
			return "200";
		}
	    return "500";
	    
	
	    
	}
	
	/**
	 * 服务器端保存附件文件
	 * @param uf
	 * @param file
	 * @return
	 */
	private UploadFiles saveFile(UploadFiles uf,MultipartFile file){
		
		
		
		UploadFiles retUf = null;
		if((uf!=null) && (file!=null)){
			
			String filePathName = null;
			//获取文件保存相对路径
			String pathPre = this.getPathPre(null, uf.getBizcode());
			//重置文件保存名(含相对路径)
			 
			
			
			String expandName = FileUtil.getExpandName(uf.getFilename());
			//组合文件绝对路径
			
			if(expandName!=null)
				filePathName =pathPre +"/"+uf.getSavedFileName() + "."+expandName ;
			
			
			uf.setSavedFileName(filePathName);
			
			File _file = new File(getUploadBasePath()+filePathName);
			
			FileOutputStream fop = null;
			try {
				fop = new FileOutputStream(_file);
				if(!_file.exists()){
					_file.createNewFile();
				}
				byte[] bytes = file.getBytes();
				fop.write(bytes);
				fop.flush();
				fop.close();
				retUf =super.saveNoBizno(uf);				
				
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		return retUf;
	}
	
	
	/**
	 * 根据附件id下载文件
	 * @param id	附件id
	 * @param request
	 * @param respones
	 * @return
	 */
	private String exportFile(Long id,HttpServletRequest request,HttpServletResponse respones){
		
		if(id!=null){
			UploadFiles uf = this.getOne(id);
			
			if(uf!=null){
				String realfilename = uf.getFilename();
				String savedfilename = uf.getSavedFileName();
				String realPath =  getUploadBasePath() + savedfilename;
				
				File file = new File(realPath);
				
				try {
					
					respones.reset();
					String encodefilename = URLEncoder.encode(realfilename,"UTF-8");
					respones.addHeader("Content-Disposition", "attachment; filename=" + encodefilename);
					respones.addHeader("Content-Length", ""+file.length());
					
					
					respones.setCharacterEncoding("UTF-8");
					
					respones.setContentType("application/octet-stream");
//					respones.setContentType("text/html;charset=UTF-8");
//					respones.setContentType(uf.getFiletype());
					OutputStream out = new BufferedOutputStream(respones.getOutputStream());
					FileInputStream fis = new FileInputStream(file);
					byte[] buffer = new byte[fis.available()];
					fis.read(buffer);
					fis.close();
					out.write(buffer);
					out.flush();
					out.close();
					fis.close();
					return "success";
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return null;
	}
	

	/**
	 * 文件预览
	 * @param id		附件id
	 * @param request	
	 * @param respones
	 * @return
	 */
	@RequestMapping(value = "/previewFile.action")	
	public Map<String,String> previewFile(@RequestParam(required=false)Long id){
		
		Map<String,String> retMap = new HashMap<String,String>();
		if(id!=null){
			UploadFiles uf = this.getOne(id);
			
			if(uf!=null){
				String realfilename = uf.getFilename();
				String savedfilename = uf.getSavedFileName();
				String realPath =  getUploadBasePath() + savedfilename;
				retMap.put("fileName", realfilename);
				retMap.put("id", String.valueOf(uf.getId()));
				String expandName = FileUtil.getExpandName(uf.getFilename());
				ConvertUtil.getInstances();
				retMap.put("content", ConvertUtil.convert2Html(realPath,expandName));
			}
		}
		return retMap;
	}
	
	@RequestMapping(value = "/downloadFile.action")	
	public String downloadFile(@RequestParam(required=false)Long id,HttpServletRequest request,HttpServletResponse respones){
		return this.exportFile(id, request, respones);
	}
	
	@RequestMapping(value = "/downloadFileTest.action")	
	public String exportFileTest(@RequestBody(required=false) String body,HttpServletRequest request,HttpServletResponse respones){
		
		Map<String,Object> paramMap = this.getBodyParam(body);		

		if(paramMap!=null && paramMap.containsKey("id")){
			Long id = LongUtil.getLongValue(paramMap.get("id").toString(),null);
			
			if(id!=null){
				return this.exportFile(id, request, respones);
			}
		}
		return "false";
	}
	

	@RequestMapping(value = "/getImage.action")	
	public void getImage(@RequestBody(required=false) String body,HttpServletRequest request,HttpServletResponse response){
		
		Map<String,Object> paramMap = this.getBodyParam(body);
		
				
		if(paramMap!=null && paramMap.containsKey("id")){
			Long id = LongUtil.getLongValue(paramMap.get("id").toString(),null);
			
			if(id!=null){
				getImage(id,null,null,request,response);
				
			}
		}
		
	}
	
	
	/**
	 * 向下兼容取图片文件函数
	 * @param id
	 * @param request
	 * @param response
	 */
	public void getImage(Long id,HttpServletRequest request,HttpServletResponse response){
		//初始化高度和宽度
		Integer w=600;
		Integer h=400;
		getImage(id,w,h,request,response);
	}
	
	/**
	 * 获取缩放图片并回写response
	 * @param id	附件id
	 * @param w		图片缩放宽度
	 * @param h		图片缩放高度
	 * @param request
	 * @param response
	 */
	public void getImage(Long id,Integer w,Integer h,HttpServletRequest request,HttpServletResponse response){
		
		
		
		
//		String realPath = request.getSession().getServletContext().getRealPath(uploadPath);
		String realPath = null;
		if(id!=null){
			BufferedImage staticImg = SysConfig.getSlideImage(id);
			if(staticImg!=null){
				
				flushImg(response,staticImg);	        
				
			}else{
			UploadFiles uf = this.getOne(id);
			
			if(uf!=null){
				
				String savedfilename = uf.getSavedFileName();
				if(savedfilename!=null){
					int _index = savedfilename.indexOf("/");
					if(_index!=0){
						savedfilename = "/"+savedfilename;
					}
				}
				realPath = getUploadBasePath() + savedfilename;
				
				File file = new File(realPath);
				BufferedImage img =null;
				try {
					
					img = ImageIO.read(file);
				} catch (IOException e) {
					// TODO Auto-generated catch block
//					e.printStackTrace();
					logger.error("file: " + realPath+" not found ...");;
				}
				if(img!=null){
					long fl = file.length();
					if(file.length()>200000){
						ScaleImgUtil is = new ScaleImgUtil();
						img = is.imageZoomOut(img, w, h, true);
						
					}
					SysConfig.setSlideImage(id,img);
					
					flushImg(response,img);
				}
				
			}
			}
		}		
	}
	
	/**
	 * 输出图片到输出流
	 * @param response
	 * @param img
	 */
	private void flushImg(HttpServletResponse response,BufferedImage img){
		
			
		response.reset();		
		
		response.setContentType("image/png");	
		
        
        try {
			ImageIO.write(img, "jpeg", response.getOutputStream());
			response.flushBuffer();	
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}		
		
	}
	
	/**
	 * 获取指定路径静态文件列表
	 */
	@RequestMapping("/getExternalFileList.action")
	public List<Map<String,String>>  getExternalFileList(){
		String staticFilePath = "/static";
		String realPath =  getUploadBasePath() + staticFilePath;
		File file=new File(realPath);
		File[] tempList = file.listFiles();
		List<Map<String,String>> lists = new ArrayList<Map<String,String>>();
		if(tempList!=null && tempList.length>0){
			for(File f:tempList){
				Map<String,String> map = new HashMap<String,String>();
				map.put("name", f.getName());				
				lists.add(map);
			}
		}
		
		return lists;
	}
	
	/**
	 * 获取附加软件资源并回写response
	 * @param body 传递参数
	 * @param request	
	 * @param response
	 */
	@RequestMapping("/getExternalFile.action")
	public void getExternalFile(@RequestParam(required=false) String fileName,HttpServletRequest request,HttpServletResponse response){
		
				
				String staticFilePath = "/static";
				String realPath =  getUploadBasePath() + staticFilePath;
				
				
				
				
				String realfilename = null;
				String decodeFileName = null;
				
				if(fileName!=null){
					try{
						decodeFileName = java.net.URLDecoder.decode(fileName,"UTF-8");
					}catch(Exception e){
						e.printStackTrace();
					}
					realfilename =realPath +"/"+ decodeFileName;
					File file = new File(realfilename );	
					
					response.reset();						
					response.addHeader("Content-Disposition", "attachment; filename=" + fileName);
					response.addHeader("Content-Length", ""+file.length());
					
					
					response.setCharacterEncoding("UTF-8");
					
					response.setContentType("application/octet-stream");
					try {						
						
	
						OutputStream out = new BufferedOutputStream(response.getOutputStream());
						FileInputStream fis = new FileInputStream(file);
						byte[] buffer = new byte[fis.available()];
						fis.read(buffer);
						fis.close();
						out.write(buffer);
						out.flush();
						out.close();
						fis.close();
						
					} catch (FileNotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
		
					
				}
		
	}
	
	/**
	 * 更新附件暂存id为实际id值，用于处理表单保存前的附件暂存处理
	 * @param bizcode	业务编码
	 * @param oldBizno	临时id
	 * @param newBizno	保存后的实际id
	 * @return
	 */
	public RetDomain updateTmpid(String bizcode,String oldBizno,String newBizno){
		
		RetDomain ret = null;
		if(bizcode !=null && oldBizno !=null && newBizno!=null){
			//定义查询参数
			Map<String,String> map = new HashMap<String,String>();
			map.put("bizno_in", oldBizno);
			map.put("bizcode", bizcode);
			//执行查询
			List<UploadFiles> lists =qryUploadService.getList(map);
			for(UploadFiles f:lists){
				if(f!=null){
					f.setBizno(newBizno);
				}
			}
			
			this.saveList(lists);
			
			ret = RetDomain.successDomain("操作成功");
			
		}else{
			ret = RetDomain.errorDomain("参数异常");
		}
		
		return ret;
	}
	
	/**
	 * 获取附件路径前缀
	 * @param bizcode
	 * @return
	 */
	private String getPathPre(String path,String bizcode){
		//路径判断
		if(path==null){
			path = getUploadBasePath();
		}
		
		if(bizcode==null){
			bizcode = upload_bizcode;
		}
		//获取日期
		Date date = new Date();
		SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
		String datStr = format.format(date);
		
		String pathPre = String.format("/%1$s/%2$s", bizcode,datStr);
		

		File fp = new File(getUploadBasePath() +pathPre);
		if(!fp.exists()){
			fp.mkdirs();
		}
		
		return pathPre;
		
	}
	
	/**
	 * 获取文件上传根目录
	 * @return
	 */
	private String getUploadBasePath(){
		String path = SysConfig.getConfig("upload_path");
		if(path==null){
			path = upload_path;
		}
		return path;
	}

	
	
	
	
}
